import { AfterViewInit, Component, OnInit, TemplateRef } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RoleDto } from 'src/app/models/sys/role.dto';
import { FormBuilder, FormControl, UntypedFormControl, UntypedFormGroup, Validators } from '@angular/forms';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalService } from 'ng-zorro-antd/modal';
import { ApiService } from 'src/app/services/api.service';
import { RoleQueryParam } from 'src/app/models/param/role-query.param';
import { Consts } from 'src/app/consts/consts';
import { NzTableQueryParams } from 'ng-zorro-antd/table';
import { NzButtonSize } from 'ng-zorro-antd/button';
import { BehaviorSubject } from 'rxjs';
import { EditMode } from 'src/app/models/enums/edit-mode.enum';
import { ClientDto } from 'src/app/models/sys/client.dto';
import { ClientQueryParam } from 'src/app/models/param/client-query.param';
import { ContentHeaderService } from 'src/app/services/content-header.service';

  // Const form names
const CLIENT_ID = 'clientId';
const ROLE_NAME = 'roleName';
const ROLE_KEY = 'roleKey';
const ENABLED = 'enabled';

@Component({
  selector: 'app-role',
  templateUrl: './role.component.html',
  styleUrl: './role.component.less'
})
export class RoleComponent implements OnInit, AfterViewInit {
  searchForm!: UntypedFormGroup;
  submitted = false;

   // Modal
   modeSubject = new BehaviorSubject<{ mode: EditMode, roleId?: number }>({ mode: EditMode.ADD, roleId: undefined });

  // 对话框title
  editTitle?: string;
  roleName?: string;

    // 详情
    roleSubject = new BehaviorSubject<RoleDto>(new RoleDto());

  // Role Table
  roles: RoleDto[] = [];
  pageIndex = 1;
  pageSize = 12;
  total = 0;

  // Modal 角色数据权限
  dataPermSubject = new BehaviorSubject<number>(0);

  clients: ClientDto[] = [];

  constructor(private _api: ApiService,
    private _fb: FormBuilder,
    private _modal: NzModalService,
    private _message: NzMessageService,
    private _contentHeader: ContentHeaderService) {}

    ngAfterViewInit(): void {
      setTimeout(() => {
        this._contentHeader.header.next('角色管理');
      });
    }

  ngOnInit(): void {
    this.createSearchForm();
    this.getClients();
    this.onSearch();
  }

  createSearchForm() {
    this.searchForm = this._fb.group({});
    this.searchForm.addControl(CLIENT_ID, new UntypedFormControl(''));
    this.searchForm.addControl(ROLE_NAME, new UntypedFormControl('', [Validators.maxLength(20)]));
    this.searchForm.addControl(ROLE_KEY, new UntypedFormControl('', [Validators.maxLength(20)]));
    this.searchForm.addControl(ENABLED, new UntypedFormControl(''));
  }

  onSearch() {
    this.submitted = true;
    if (!this.searchForm.valid) {
      return;
    }

    const param = new RoleQueryParam();
    param.clientId = this.searchForm.get(CLIENT_ID)?.value;
    param.roleName = this.searchForm.get(ROLE_NAME)?.value;
    param.roleKey = this.searchForm.get(ROLE_KEY)?.value;
    param.enabled = this.searchForm.get(ENABLED)?.value;
    param.pageNum = this.pageIndex;
    param.pageSize = this.pageSize;

    this._api.getRoleList(param).subscribe((resp) => {
      if (resp.code == Consts.RESP_OK && resp.data) {
        this.roles = resp.data;
        this.total = resp.total;

        this.submitted = false;
      }
    });
  }

  get fm() {
    return this.searchForm.controls;
  }

  onPageParamChange(params: NzTableQueryParams) {
    this.pageIndex = params.pageIndex;
    this.pageSize = params.pageSize;
    this.onSearch();
  }

  onCreate(tplTitle: TemplateRef<object>, tplContent: TemplateRef<object>) {
    this.editTitle = '创建角色';
    this.roleName = undefined;

    this._modal.create({
      nzTitle: tplTitle,
      nzContent: tplContent,
      nzFooter: null,
      nzMaskClosable: false,
      nzClosable: false,
      nzWidth: 800,
      nzOnOk: () => {
        console.log('Role added');
      }
    });

    this.modeSubject.next({ mode: EditMode.ADD, roleId: undefined });
  }

  onUpdate(tplTitle: TemplateRef<object>, tplContent: TemplateRef<object>, role: RoleDto) {
    this.editTitle = '编辑角色';
    this.roleName = role.roleName;

    this._modal.create({
      nzTitle: tplTitle,
      nzContent: tplContent,
      nzFooter: null,
      nzMaskClosable: false,
      nzClosable: false,
      nzWidth: 800,
      nzOnOk: () => {
        console.log('Role updated');
      }
    });

    this.modeSubject.next({ mode: EditMode.EDIT, roleId: role.roleId });
  }

  onDetail(tplTitle: TemplateRef<object>, tplContent: TemplateRef<object>, role: RoleDto) {
    this.editTitle = '角色详情';

    this._modal.create({
      nzTitle: tplTitle,
      nzContent: tplContent,
      nzFooter: null,
      nzMaskClosable: false,
      nzClosable: false,
      nzWidth: 1024,
      nzOnOk: () => {
        console.log('groupType detail');
      }
    });

    this.roleSubject.next(role);
  }

  onDelete(roleId: number) {
    this._api.deleteRole(roleId).subscribe((resp) => {
      if (resp.code == Consts.RESP_OK) {
        this._message.info("删除角色成功");
        this.onSearch();
      } else {
        this._message.warning("删除角色失败: " + resp.message);
      }
    });
  }

  onDataPerms(tplTitle: TemplateRef<object>, tplContent: TemplateRef<object>, role: RoleDto) {
    console.log('OnDataPerms');

    this._modal.create({
      nzTitle: "设置角色数据权限",
      nzContent: tplContent,
      nzFooter: null,
      nzMaskClosable: false,
      nzClosable: false,
      nzWidth: 800,
      nzOnOk: () => {
        console.log('Role updated');
      }
    });

    this.dataPermSubject.next(role.roleId);
  }
      
  onReset() {
    this.searchForm.get(CLIENT_ID)?.setValue(undefined);
    this.searchForm.get(ROLE_NAME)?.setValue(undefined);
    this.searchForm.get(ROLE_KEY)?.setValue(undefined);
    this.searchForm.get(ENABLED)?.setValue(undefined);
  }

  onAddRoleEvent(result: boolean) {
    console.log(`add role result ${result}`);
    if (result) {
      this.onSearch();
    }

    this._modal.closeAll();
  }

  onDataPermEvent(result: boolean) {
    console.log(`set data perm result ${result}`);

    this._modal.closeAll();
  }

  getClients() {
    const param = new ClientQueryParam();
    this._api.getClientList(param).subscribe((resp) => {
      if (resp.code == Consts.RESP_OK && resp.data) {
        this.clients = resp.data;
      }
    });
  }

  onDetailEvent(result: boolean) {
    this._modal.closeAll();
    console.log(`${result}`);
  }
}
